package com.skillworld.webapp.web.pages.rest.school;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.courseservice.CourseService;
import com.skillworld.webapp.model.enrollment.ReleasedExam.Grade;
import com.skillworld.webapp.model.util.PermissionDeniedException;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.Parameter;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@ContentType("text/xml")
public class EvaluateExam
{

	@SuppressWarnings("unused")
    @Property
    private String errorMessage = null;
    
    @Inject
    private CourseService courseService;
	
    @SessionState(create=false)
    private UserSession userSession;
   
    private boolean userSessionExists;
   
    @Inject
    private Request request;
    
    
    void onPassivate()
    { 
        return; 
    }
    
    void onActivate()
    {        
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }

        String examinationParam = request.getParameter("examination");
        String gradeParam = request.getParameter("grade");
        String commentary = request.getParameter("commentary");
        
        if (examinationParam == null || gradeParam == null || commentary == null)
        { 
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }  

    	try
    	{ 
    	    long examinationId = Long.parseLong(examinationParam);
            Grade grade = Parameter.parseGrade(gradeParam);
    	    courseService.evaluateExam(examinationId, userSession.getUserId(), 
    	                                grade, commentary);
	    }
        catch(NumberFormatException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (IllegalArgumentException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
    	catch (InstanceNotFoundException e)
    	{ errorMessage = ErrorMessages.INSTANCE_NOT_FOUND; }
    	catch (PermissionDeniedException e)
    	{ errorMessage = ErrorMessages.PERMISSION_DENIED; }
    }
}
